<?php
namespace app\home\controller;

use app\common\controller\Home;
use app\common\model\Business\Business;
use app\common\model\Business\Collection;
use app\common\model\Business\Commission;
use app\common\model\Business\Record;
use app\common\model\Coupon\Coupon;
use app\common\model\Coupon\Receive;
use app\common\model\Subject\Chapter;
use app\common\model\Subject\Comment;
use app\common\model\Subject\Order;
use app\common\model\Subject\Subject;
use think\Request;

class Course extends Home{
    public function __construct(Request $request)
    {
        $this->noLogin = ['index'];
        parent::__construct($request);
    }
    public function index(Request $request)
    {
        if($request->isGet()){
            return $this->fetch();
        }
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
        $keyword = $request->post('keyword')?trim($request->post('keyword')):'';
        $teacherid = $request->post('id')?trim($request->post('id')):'';
        // $where = $teacherid?['teacherid'=>$teacherid,'title'=>['like','%'.$keyword.'%']]:['title'=>['like','%'.$keyword.'%']];
        $where = [];
        $teacherid?($where['teacherid']=$teacherid):null;
        $keyword?($where['title']=['like','%'.$keyword.'%']):null;
        $subject = Subject::where($where)
                ->order('createtime','desc')
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();

        // $subject = Subject::whereRaw("title like binary '%".$keyword."%'")
        // ->order('createtime','desc')
        // ->limit(($pageNum-1)*$pageSize,$pageSize)
        // ->select();

        $page = [];
        $page['curPageData'] = $subject;
        $page['totalPage'] = ceil(Subject::where($where)->count()/$pageSize);
        return $page;
    }
    public function details(Request $request)
    {
        $subjectid = $request->param('id');
        if(!$subjectid){
            return $this->error('请求失敗','/home/subject');
        }
        $subject = Subject::where('id',$subjectid)->find();
        // halt($subject);
        if(!$subject){
            return $this->error('请求失敗','/home/subject');
        }
        $busid = $this->business['id'];
        $this->assign('subject',$subject);
        
        
        $isLike = in_array($busid,$subject['likes']?explode(',',$subject['likes']):[]);
        if($request->isGet()){
            $this->assign('isLike',$isLike);

            $isCollection = true&&Collection::where(['status'=>'subject','collectid'=>$subject['id']])->find();
            // halt($isCollection);
            $this->assign('isCollection',$isCollection);

            $isPay = true&&Order::where(['busid'=>$busid,'subid'=>$subjectid])->find();
            $this->assign('isPay',$isPay);
            // halt($isPay);

            return $this->fetch();
        }
        $status = ['code'=>0];
        if($request->isPost()){
            if($isLike){
                $likes = join(',',array_filter(explode(',',$subject['likes']),function($like){return $like!=$this->business['id'];}));
                // halt($likes);
                $subject['likes'] = $likes;
                $result = $subject->save();
                if($result){
                    $status['code'] = 1;
                    $status['msg'] = '取消成功';
                    $status['isLike'] = false;
                }else{
                    $status['msg'] = '取消失败';
                }
            }else{
                $likeList = trim($subject['likes'])?explode(',',$subject['likes']):[];
                array_push($likeList,$this->business['id']);
                // halt($likeList);
                $likes = join(',',$likeList);
                $subject['likes'] = $likes;
                $result = $subject->save();
                if($result){
                    $status['code'] = 1;
                    $status['msg'] = '点赞成功';
                    $status['isLike'] = true;
                }else{
                    $status['msg'] = '点赞失败';
                }
            }
            return $status;
        }
    }
    public function confirm(Request $request)
    {
        $subid = $request->param('id');
        $subject = Subject::where('id',$subid)->find();
        if(!$subject){
            $this->error('找不到课程','/');
        }
        $busid = $this->business['id'];
        if($request->isGet()){
            $this->assign('money',$this->business['money']);
            $subject = Subject::where('id',$subid)->find();
            // halt($subject);
            $this->assign('subject',$subject);
            $coupons = [];
            $receives = Receive::where(['busid'=>$busid,'status'=>1])->select();
            foreach($receives as $receive){
                if(time()>$receive['coupon']['createtime']&&time()<$receive['coupon']['endtime']){
                    $coupons[] =  $receive['coupon'];
                }
            }
            // halt($coupons);
            $this->assign('coupons',$coupons);
            $payTypes = [
                'money'=>'余额',
                'wx'=>'微信',
                'zfb'=>'支付宝'
            ];
            $this->assign('payTypes',$payTypes);
            return $this->fetch();
        }
        $payType = $request->param('payType');
        $payType = isset($payType)?trim($payType):'money';

        $cid = $request->param('coupon');
        $cid = isset($cid)?(int)$cid:0;
        $receive = Receive::where(['cid'=>$cid,'busid'=>$busid])->find();
        if($receive&&time()<$receive['coupon']['createtime']&&time()>$receive['coupon']['endtime']){
            $this->error('优惠券不可用','/home/course/confirm?id='.$subid);
        }
        $rate = $receive?$receive['coupon']['rate']:1;
        $total = $subject['price']*$rate;
        if($payType=='money'){
            $money = $this->business['money'];
            if($total>$money){
                $this->error('余额不足','/home/course/confirm?id='.$subid);
            }else{
                Business::startTrans();
                Order::startTrans();
                Record::startTrans();
                Commission::startTrans();
                Receive::startTrans();
                $result = true;
                try{
                    $data = [
                        'subid'=>$subid,
                        'busid'=>$this->business['id'],
                        'total'=>$total,
                        'code'=>'ST'.date('YmdHis',time()).random_int(1000000,9999999),
                        'pay'=>$payType
                    ];
                    $order = Order::create($data);
                    $this->business['money'] = $this->business['money']-$total;
                    $this->business->save();
                    if($receive){
                        $receive['status'] = 0;
                        $receive->save();
                    }
                    if($this->business['parentid']){
                        $data = [
                            'orderid'=>$order['id'],
                            'busid'=>$busid,
                            'parentid'=>$this->business['parentid'],
                            'amount'=>$total*config('site.amountRate'),
                            'type'=>'subject',
                            'status'=>0,
                        ];
                        Commission::create($data);
                    }
                    $data = [
                        'total'=>$total,
                        'content'=>'购买课程：【'.$subject['title'].'】花费了 ￥'.$total.' 元',
                        'busid'=>$busid
                    ];
                    Record::create($data);
                    // 提交事务
                    Business::commit();
                    Order::commit();
                    Record::commit();
                    Commission::commit();
                    Receive::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    $result = false;
                    Business::rollback();
                    Order::rollback();
                    Record::rollback();
                    Commission::rollback();
                    if($receive){
                        Receive::rollback();
                    }
                }
                if($result){
                    $this->success('支付成功','/home/course/details?id='.$subid);
                }else{
                    $this->error('支付失败','/home/course/confirm?id='.$subid);
                }
            }
        }
    }
    public function comment(Request $request)
    {
        $pageNum = $request->post('pageNum')?$request->post('pageNum'):1;
        $pageSize = $request->post('pageSize')?$request->post('pageSize'):5;
        $subid = $request->post('id');
        $where = ['subid'=>$subid];
        $commission = Comment::where($where)
                ->order('createtime','desc')
                ->limit(($pageNum-1)*$pageSize,$pageSize)
                ->select();

        $page = [];
        $page['curPageData'] = $commission;
        $page['totalPage'] = ceil(Comment::where($where)->count()/$pageSize);
        return $page;
    }
    public function chapter(Request $request)
    {
        $status = [];
        $chapterid = $request->post('chapterid');
        $chapter = Chapter::where('id',$chapterid)->find();
        if(!$chapter){
            $status = ['code'=>0,'msg'=>'章节不存在'];
            return $status;
        }
        $order = Order::where(['busid'=>$this->business['id'],'subid'=>$chapter['subid']])->find();
        if(!$order){
            $status = ['code'=>0,'msg'=>'章节无权访问'];
            return $status;
        }
        $status = ['code'=>1,'msg'=>$chapter['url_text']];
        return $status;
    }
}